#!/usr/bin/python

# This file is part of Nappy (Navit add poi with python)
#
# Nappy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Nappy Copyright (C) 2009 Paolo Alberti <paolo.alberti_at_gmail.com>


#
# look at the MyPoi.txt address: here is set to ~/opt/navit/navit/maps/MyPoi.txt
# if you need a different address of the file, change the variable MyPoiFile
# with the desired location
#

import urllib2
import string

# control variable
exists=""

# address of MyPoi.txt file
MyPoiFile = "~/opt/navit/navit/maps/MyPoi.txt"

# gets data from user
address = raw_input("write city, address and number separated with spaces: ")
description = raw_input("write the description of the poi: ")

# builds the url to pass to yahoo map service
url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=capelinks&location=" + address.replace(" ", "+") + "&Geocode=Geocode"

# sends the request and gets the response
req = urllib2.Request(url)
response = urllib2.urlopen(req)
xml = response.read()

# parses the results
a = string.find(xml, "<Latitude>")
b = string.find(xml, "<Longitude>")
lat = xml[a+10:a+19]
lon = xml[b+11:b+20]

print "lat = " + str(lat)
print "lon = " + str(lon)

# set the strings to pass to MyPoi.txt file
l_first = 'type="poi_viewpoint" label="' + description + '" description="' + description + '"'
l_second = str(lon) + " " + str(lat)

# check if the poi already exists
fileHandle = open ( "/home/glider/opt/navit/navit/maps/MyPoi.txt" )
fileList = fileHandle.readlines()
fileHandle.close()
for fileLine in fileList:
   if fileLine == l_second + '\n':
	exists="yes"
	break
if exists=="yes":
    print "there is a poi with the same coordinates in MyPoi.txt"
    print "can't continue"
    print "check your coordinates and repeat the process"
    print "exiting..."    
else:
    # if it doesn't exist, inserts it to MyPoi.txt
    fileHandle = open ( "/home/glider/opt/navit/navit/maps/MyPoi.txt", 'a' )
    fileHandle.write ( l_first + '\n')
    fileHandle.write ( l_second + '\n')
    fileHandle.close() 

print "New Poi added!"
